/*
 * Copyright 2011 Romain Gilles
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jvdb;

import java.sql.Timestamp;
import java.util.Calendar;

/**
 * convert a {@code Timestamp} into the following String format: yyyy/MM/dd HH:mm:ss:SSS
 */
class TimestampConverter extends DateConverter<Timestamp> implements Converter {
    private static final int FORMAT_SIZE = 25;

    private TimestampConverter(Timestamp value, Calendar calendar) {
        super(value, calendar);
    }

    @Override
    StringBuilder doConvert(Calendar cal, StringBuilder result) {
        super.doConvert(cal, result);
        return formatTime(cal, result);
    }

    static StringBuilder formatTime(Calendar cal, StringBuilder result) {
        result.append(' ');
        append2DigitField(result, cal, Calendar.HOUR_OF_DAY).append(':');
        append2DigitField(result, cal, Calendar.MINUTE).append(':');
        append2DigitField(result, cal, Calendar.SECOND).append(':');
        append3DigitField(result, cal, Calendar.MILLISECOND);
        return result;
    }

    @Override
    int getFormatSize() {
        return FORMAT_SIZE;
    }

    private static StringBuilder append3DigitField(StringBuilder result, Calendar cal, int field) {
        int fieldValue = cal.get(field);
        if (fieldValue < 100)
            result.append('0');
        if (fieldValue < 10)
            result.append('0');
        result.append(fieldValue);
        return result;
    }

    static TimestampConverter newInstance(Timestamp value, Calendar cal) {
        return new TimestampConverter(value, cal);
    }

    static TimestampConverter newInstance(Timestamp value) {
        return new TimestampConverter(value, null);
    }
}
